<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * This is a sample module for PyroCMS
 *
 * @author 		Jerel Unruh - PyroCMS Dev Team
 * @website		http://unruhdesigns.com
 * @package 	PyroCMS
 * @subpackage 	Sample Module
 */
class User_m extends MY_Model {

	public function __construct()
	{
		parent::__construct();
		$this->load->library('module_helper');
	}

	function listall(){
		$total = count( $this->user_entity->getArrayListOfUser() );
					
		$records_per_page = isset($_GET['records_per_page']) ? intval($_GET['records_per_page']) : 25;
		$per_page = isset($_GET['per_page']) ? intval($_GET['per_page']) : 0;
		
		$partial = array();
		foreach($_GET as $key=> $value){
			if($key != "per_page")
				$partial["$key"] = "$key=$value";
		}
		
		$pagination = create_pagination( 
								$uri = 'admin/dataman/user/listall/?'.implode('&',$partial), 
								$total_rows = $total , 
								$limit= $records_per_page,
								$uri_segment = 0,
								TRUE, TRUE 
							);
		if(!isset($_GET['s'])){
			$sort = 'id';
		}else{
			if(!in_array($_GET['s'], array('cash','coin','bonus','created_time'))){
				$sort = 'id';
			}else{
				$sort = $_GET['s'];
			}
		}		
		
		if(!isset($_GET['o'])){
			$order = 'asc';
		}else{
			if(!in_array($_GET['o'], array('asc','desc'))){
				$order = 'asc';
			}else{
				$order = $_GET['o'];
			}
		}	
		 
	 	$records = $this->db->select("*")->
						from(TBL_USER)->
						order_by($sort,$order)->
						limit($records_per_page, $per_page )->
						get()->result() ; 
		return array('pagination'=> $pagination, 'items'=>$records, 'total_records'=>$total);
	}
	
	function search(){
		$s = ($_GET['key']);
		$filter = ($_GET['filter']);
		$options = array('username'=>'User name','email'=>'Email','country'=>'Country','login_ip'=>'Signup IP');
		if(!in_array($filter, array_keys($options))){
			$filter = 'username';
		}
		
		$records_per_page = isset($_GET['records_per_page']) ? intval($_GET['records_per_page']) : 25;
		$per_page = isset($_GET['per_page']) ? intval($_GET['per_page']) : 0;
		
		$total = count( $this->db->where(array("$filter"=>$s))->get(TBL_USER)->result() );
	
		$partial = array();
		foreach($_GET as $key=> $value){
			if($key != "per_page")
				$partial["$key"] = "$key=$value";
		}
		
		$pagination = create_pagination( 
								$uri = 'admin/dataman/user/listall/?'.implode('&',$partial), 
								$total_rows = $total , 
								$limit= $records_per_page,
								$uri_segment = 0,
								TRUE, TRUE 
							);
		if(!isset($_GET['s'])){
			$sort = 'id';
		}else{
			if(!in_array($_GET['s'], array('cash','coin','bonus','created_time'))){
				$sort = 'id';
			}else{
				$sort = $_GET['s'];
			}
		}		
		
		if(!isset($_GET['o'])){
			$order = 'asc';
		}else{
			if(!in_array($_GET['o'], array('asc','desc'))){
				$order = 'asc';
			}else{
				$order = $_GET['o'];
			}
		}	
		
		$records = $this->db->where(array("$filter"=>$s))->
							order_by($sort,$order)->
							limit($records_per_page, $per_page )->
							get(TBL_USER)->result();				
		return array('pagination'=> $pagination, 'items'=>$records, 'total_records'=>$total);
	}
	
	function change_user_status(){
		$this->db->where('id',intval($_POST['user_id']))->update(TBL_USER, array('status'=>$_POST['status']));
		$this->session->set_flashdata('success', lang('dataman.success'));
		echo 'ok';
		exit();
	}
	
	function edit_submit(){
		if(isset($_POST['user_id'])){
			$USER = clone_( $this->user_entity->init('id',intval($_POST['user_id'])) );
			$myavatar = $USER->getAvatar();
			
			$username = $_POST['username'];
			$email = $_POST['email'];
			
			$U1 = clone_( $this->user_entity->init('username',$username) );
			$U2 = clone_( $this->user_entity->init('email',$email) );
			if($U1 AND $U1->getId() != $USER->getId()){
				echo "Username is not valid.";exit();
			}
			
			if($U2 AND $U2->getId() != $USER->getId()){
				echo "Email is not valid.";exit();
			}
			
			if(! $this->phpvalidator->is_decimal($_POST['cash'])){
				echo "Cash is not valid";exit();
			}
			
			if(! $this->phpvalidator->is_natural($_POST['coin'])){
				echo "Coin is not valid";exit();
			}
			
			if(! $this->phpvalidator->is_natural($_POST['bonus'])){
				echo "Bonus is not valid";exit();
			}
			
			if(isset($_FILES["avatar"]) AND !empty($_FILES["avatar"]['name'])) {
				if(($_FILES["avatar"]['size']/1000000) > allowMaxFileSize() ){
					$myavatar = '';
				}else{
					$myavatar = $this->module_helper->uploadFile( 
											$_FILES["avatar"]['tmp_name'],
											$_FILES["avatar"]['name'],
											$USER->getFolderFileStorage(),
											allowExtensionPictureUpload()
										);
				}	
			}
			
			$USER->setUserName($username);
			$USER->setEmail($email);
			$USER->setPassword($_POST['password']);
			$USER->setFullName($_POST['fullname']);
			$USER->setCity($_POST['city']);
			$USER->setState($_POST['state']);
			$USER->setCountry($_POST['country']);
			$USER->setMobile($_POST['mobile']);
			$USER->setCash($_POST['cash']);
			$USER->setCoin($_POST['coin']);
			$USER->setBonus($_POST['bonus']);
			$USER->setUpdatedTime(time());
			$USER->setAvatar($myavatar);
			
			$USER->update();
		}else{
			
			$username = $_POST['username'];
			$email = $_POST['email'];
			
			$U1 = clone_( $this->user_entity->init('username',$username) );
			$U2 = clone_( $this->user_entity->init('email',$email) );
			if($U1){
				echo "Username is not valid.";exit();
			}
			
			if($U2){
				echo "Email is not valid.";exit();
			}
			
			if(! $this->phpvalidator->is_decimal($_POST['cash'])){
				echo "Cash is not valid";exit();
			}
			
			if(! $this->phpvalidator->is_natural($_POST['coin'])){
				echo "Coin is not valid";exit();
			}
			
			if(! $this->phpvalidator->is_natural($_POST['bonus'])){
				echo "Bonus is not valid";exit();
			}
			$myavatar = '';
			if(isset($_FILES["avatar"]) AND !empty($_FILES["avatar"]['name'])) {
				if(($_FILES["avatar"]['size']/1000000) > allowMaxFileSize() ){
					$myavatar = '';
				}else{
					$myavatar = $this->module_helper->uploadFile( 
											$_FILES["avatar"]['tmp_name'],
											$_FILES["avatar"]['name'],
											$USER->getFolderFileStorage(),
											allowExtensionPictureUpload()
										);
				}	
			}
			$id = $this->user_entity->createNewUserEntity($username);
			$USER = $this->user_entity->init('id',$id);
			
			$USER->setUserName($username);
			$USER->setEmail($email);
			$USER->setPassword($_POST['password']);
			$USER->setFullName($_POST['fullname']);
			$USER->setCity($_POST['city']);
			$USER->setState($_POST['state']);
			$USER->setCountry($_POST['country']);
			$USER->setMobile($_POST['mobile']);
			$USER->setCash($_POST['cash']);
			$USER->setCoin($_POST['coin']);
			$USER->setBonus($_POST['bonus']);
			$USER->setCreatedTime(time());
			$USER->setUpdatedTime(time());
			$USER->setAvatar($myavatar);
			$USER->setReferralCode($this->digit->generateReferralCode());
			$USER->setStatus('activated');
			if( strtolower( $this->input->post('country','') ) == 'india'){
				$USER->setCurrencyCode('ind');
			}else{
				$USER->setCurrencyCode('usd');
			}
			$USER->update();
		}	
		$this->session->set_flashdata('success', lang('dataman.success'));
		echo 'ok';exit();
	}
	
	function show_shipping_info(){
		$USER = $this->user_entity->init('id',intval($_POST['user_id']));
		$SHIPPING = $this->shipping_entity->init('user_id',$USER->getId());
		if($SHIPPING){
			echo $SHIPPING->getCourierName();
			exit();
		}else{
			echo '';
			exit();
		}
	}
	
	function delete_user(){
		$id = $this->input->post('user_id',TRUE);
		$this->db->where('id',$id)->delete(TBL_USER);
		$this->session->set_flashdata('success', lang('dataman.success'));
		exit();
	}
	
//end class	
}
